import { FlowTemplateDao } from '@apps/flow/domain/flow-template/flow-template.dao'
import { DomainModel } from '@apps/flow/domain/model'
import { AppConfig } from '@apps/server/config/entity/app-config.entity'
import { CoreConfigService } from '@libs/lhy-core'
import { Injectable } from '@nestjs/common'
import { FlowTemplateTreeDto } from './dto/flow-template-tree.dto'
import { FlowTemplateTreeVo } from './vo/flow-template-tree.vo'

@Injectable()
export class FlowTemplateService {
  constructor(
    private readonly templateDao: FlowTemplateDao,
    private configService: CoreConfigService<AppConfig>
  ) {}

  /**
   * 获取模板树
   * @param param
   * @returns
   */
  async tree(param: FlowTemplateTreeDto) {
    const platformData = await this.templateDao.list({
      platform: param.platform,
      project: param.project,
      belong: DomainModel.FlowTemplateBelong.Platform,
    })
    const systemData = await this.templateDao.list({
      platform: param.platform,
      project: param.project,
      belong: DomainModel.FlowTemplateBelong.System,
    })

    const vos: FlowTemplateTreeVo[] = []
    const voMap = new Map<string, FlowTemplateTreeVo>()
    const eachData = (item: DomainModel.FlowTemplate) => {
      if (voMap.has(item.groupLabel)) {
        voMap.get(item.groupLabel)?.templates.push(item)
      } else {
        const vo = new FlowTemplateTreeVo()
        vo.id = vos.length + 1
        vo.groupLabel = item.groupLabel
        vo.templates = [item]

        voMap.set(item.groupLabel, vo)
        vos.push(vo)
      }
    }

    systemData.forEach(eachData)
    platformData.forEach(eachData)

    return vos
  }
}
